import Toast from 'tdesign-miniprogram/toast/index';
// 接口
import { fetchShopSearchindex, fetchShopDelSearchHistory } from '~/request/api';

Page({
  data: {
    historyWords: [],
    popularWords: [],
    searchValue: '',
    dialog: {
      title: '确认删除当前历史记录',
      showCancelButton: true,
      message: '',
    },
    dialogShow: false,
  },

  deleteType: 0,
  deleteIndex: '',

  onShow() {
    this.getShopSearchindex();
    // this.queryHistory();
    // this.queryPopular();
  },

  // 获取历史搜索及热门搜索
  async getShopSearchindex() {
    try {
      const res = await fetchShopSearchindex();
      this.setData({
        historyWords: res.history_search,
        popularWords: res.hot_search,
      });
    } catch (error) {
      console.log(error);
    }
  },

  // 删除记录
  async ShopDelSearchHistory() {
    try {
      const res = await fetchShopDelSearchHistory();
      Toast({
        context: this,
        selector: '#t-toast',
        message: res.msg,
      });
      // this.getShopSearchindex();
      this.setData({ historyWords: [], dialogShow: false });
    } catch (error) {
      console.log(error);
    }
  },

  confirm() {
    const { historyWords } = this.data;
    const { deleteType } = this;
    if (deleteType === 0) {
      this.setData({
        historyWords,
        dialogShow: false,
      });
    } else {
      this.ShopDelSearchHistory();
    }
  },

  close() {
    this.setData({ dialogShow: false });
  },

  handleClearHistory() {
    const { dialog } = this.data;
    this.deleteType = 1;
    this.setData({
      dialog: {
        ...dialog,
        message: '确认删除所有历史记录',
      },
      dialogShow: true,
    });
  },

  handleHistoryTap(e) {
    const { historyWords } = this.data;
    const { dataset } = e.currentTarget;
    const _searchValue = historyWords[dataset.index || 0] || '';
    if (_searchValue) {
      wx.navigateTo({
        url: `/pages/goods/result/index?searchValue=${_searchValue}`,
      });
    }
  },

  handleSubmit(e) {
    const { value } = e.detail;
    if (value.length === 0) return;
    wx.navigateTo({
      url: `/pages/goods/result/index?searchValue=${value}`,
    });
  },
});
